blob: de589e50f3f4c11b118afbfb10dd711ef3dd92d6 [file]
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
use crate::{
Attachments, PendingOperationJournal, PreparedMutation, RemoteCallHandle, RemoteClientError,
RemoteHostConnection, RootId,
client::mutation_reply_result,
journal::{JournalDispatch, OperationReceipt, OperationRequest, ReceiptSource},
};
use futures_util::future::BoxFuture;
use serde_json::Value;
use std::{
collections::BTreeMap,
future::Future,
sync::{Arc, RwLock},
};
use uuid::Uuid;
/// An already admitted connection to exactly one Root.
pub trait RootTransport: Send + Sync {
fn root_id(&self) -> &str;
fn remote_calls(&self) -> Option<RemoteCallHandle> {
None
}
fn call<'a>(
&'a self,
endpoint: &'a str,
method: &'a str,
params: Value,
) -> BoxFuture<'a, Result<Value, RemoteClientError>>;
/// Prepare a mutation with the supplied durable operation ID. Dropping
/// the prepared call must leave it unconfirmed.
fn prepare_mutation<'a>(
&'a self,
op_id: Uuid,
endpoint: &'a str,
method: &'a str,
params: Value,
) -> BoxFuture<'a, Result<Box<dyn PreparedRootMutation>, RemoteClientError>>;
}
/// A prepared mutation against the original provider. The reference must be
/// stable across connections and identify the request and original binding.
/// Confirming the same reference again must observe the original receipt,
/// with the provider enforcing at-most-once execution.
pub trait PreparedRootMutation: Send {
fn reference(&self) -> &Value;
/// An explicit rejection or recorded cleanup error is terminal. Other
/// errors leave the operation eligible for reconciliation.
fn confirm(self: Box<Self>) -> BoxFuture<'static, Result<Value, RemoteClientError>>;
}
impl RootTransport for RemoteHostConnection {
fn root_id(&self) -> &str {
self.root_id()
}
fn remote_calls(&self) -> Option<RemoteCallHandle> {
Some(self.call_handle())
}
fn call<'a>(
&'a self,
endpoint: &'a str,
method: &'a str,
params: Value,
) -> BoxFuture<'a, Result<Value, RemoteClientError>> {
Box::pin(self.query(endpoint, method, params))
}
fn prepare_mutation<'a>(
&'a self,
op_id: Uuid,
endpoint: &'a str,
method: &'a str,
params: Value,
) -> BoxFuture<'a, Result<Box<dyn PreparedRootMutation>, RemoteClientError>> {
Box::pin(async move {
RootTransport::prepare_mutation(&self.call_handle(), op_id, endpoint, method, params)
.await
})
}
}
impl RootTransport for RemoteCallHandle {
fn root_id(&self) -> &str {
self.root_id()
}
fn remote_calls(&self) -> Option<RemoteCallHandle> {
Some(self.clone())
}
fn call<'a>(
&'a self,
endpoint: &'a str,
method: &'a str,
params: Value,
) -> BoxFuture<'a, Result<Value, RemoteClientError>> {
Box::pin(self.query(endpoint, method, params))
}
fn prepare_mutation<'a>(
&'a self,
op_id: Uuid,
endpoint: &'a str,
method: &'a str,
params: Value,
) -> BoxFuture<'a, Result<Box<dyn PreparedRootMutation>, RemoteClientError>> {
Box::pin(async move {
let prepared = self
.prepare_mutation_with_request(
endpoint.to_owned().into(),
method.to_owned().into(),
params,
Attachments::new(),
op_id,
)
.await?;
let reference = serde_json::from_str(prepared.reference().get())?;
Ok(Box::new(RemotePreparedRootMutation {
prepared,
reference,
}) as Box<dyn PreparedRootMutation>)
})
}
}
struct RemotePreparedRootMutation {
prepared: PreparedMutation<'static>,
reference: Value,
}
impl PreparedRootMutation for RemotePreparedRootMutation {
fn reference(&self) -> &Value {
&self.reference
}
fn confirm(self: Box<Self>) -> BoxFuture<'static, Result<Value, RemoteClientError>> {
Box::pin(
self.prepared
.confirm_with_reference(self.reference, |_| std::future::ready(())),
)
}
}
/// Routes calls using an explicit Root and persists mutation intent before sending.
pub struct FleetRouter {
transports: RwLock<BTreeMap<RootId, Arc<dyn RootTransport>>>,
journal: PendingOperationJournal,
}
impl FleetRouter {
pub fn new(journal: PendingOperationJournal) -> Self {
Self {
transports: RwLock::new(BTreeMap::new()),
journal,
}
}
/// Install or replace this Root's transport. In-flight calls retain the
/// transport they already acquired.
pub fn register(
&self,
root_id: RootId,
transport: Arc<dyn RootTransport>,
) -> Result<Option<Arc<dyn RootTransport>>, RemoteClientError> {
if transport.root_id() != root_id.as_str() {
return Err(RemoteClientError::RootIdMismatch {
expected: root_id.to_string(),
actual: transport.root_id().to_owned(),
});
}
Ok(self.transports.write().unwrap().insert(root_id, transport))
}
pub fn unregister(&self, root_id: &RootId) -> Option<Arc<dyn RootTransport>> {
self.transports.write().unwrap().remove(root_id)
}
pub fn get(&self, root_id: &RootId) -> Result<Arc<dyn RootTransport>, RemoteClientError> {
self.transports
.read()
.unwrap()
.get(root_id)
.cloned()
.ok_or_else(|| RemoteClientError::UnknownRoot(root_id.clone()))
}
pub fn roots(&self) -> Vec<RootId> {
self.transports.read().unwrap().keys().cloned().collect()
}
/// Pin the current remote session for calls or subscriptions that must
/// remain on the admission the caller already observed.
pub fn remote_calls(&self, root_id: &RootId) -> Result<RemoteCallHandle, RemoteClientError> {
self.get(root_id)?.remote_calls().ok_or_else(|| {
RemoteClientError::Protocol(format!("Root '{root_id}' has no remote session"))
})
}
pub async fn call(
&self,
root_id: &RootId,
endpoint: &str,
method: &str,
params: Value,
) -> Result<Value, RemoteClientError> {
self.get(root_id)?.call(endpoint, method, params).await
}
/// Reuse the operation ID for the same Root, scope, endpoint, method, and
/// payload. A terminal receipt is returned from the journal on repeats.
pub async fn call_idempotent(
&self,
root_id: &RootId,
op_id: Uuid,
scope: &str,
endpoint: &str,
method: &str,
params: Value,
) -> Result<Value, RemoteClientError> {
let transport = self.get(root_id);
let request = OperationRequest {
op_id,
root_id: root_id.clone(),
scope: scope.to_owned(),
endpoint: endpoint.to_owned(),
method: method.to_owned(),
params,
};
let params = match self.begin(request, transport.is_ok()).await? {
JournalDispatch::Send(params) => params,
JournalDispatch::Cached(receipt) => return receipt.into_result(),
JournalDispatch::Missing => {
return Err(RemoteClientError::UnknownRoot(root_id.clone()));
}
};
self.dispatch_mutation(transport?.as_ref(), op_id, endpoint, method, params)
.await
}
/// Journal a mutation on a pinned admission. Attachments stay in memory.
/// Callers must use receipt-only reconciliation for operations that need
/// those attachments again.
pub async fn call_remote_idempotent<F, P>(
&self,
calls: &RemoteCallHandle,
op_id: Uuid,
scope: &str,
(endpoint, method, params): (&str, &str, Value),
attachments: Attachments,
(before_confirm, on_progress, deadline): (
impl FnOnce(String) -> P,
impl FnMut(Value) -> F,
Option<tokio::time::Instant>,
),
) -> Result<Value, RemoteClientError>
where
F: Future<Output = ()>,
P: Future<Output = Result<(), String>>,
{
let root_id: RootId = calls
.root_id()
.parse()
.map_err(|error: crate::InvalidRootId| {
RemoteClientError::Protocol(error.to_string())
})?;
let request = OperationRequest {
op_id,
root_id: root_id.clone(),
scope: scope.to_owned(),
endpoint: endpoint.to_owned(),
method: method.to_owned(),
params,
};
let params = match self.begin(request, true).await? {
JournalDispatch::Send(params) => params,
JournalDispatch::Cached(receipt) => return receipt.into_result(),
JournalDispatch::Missing => return Err(RemoteClientError::UnknownRoot(root_id)),
};
let prepare = async {
let prepared = calls
.prepare_mutation_with_request(
endpoint.into(),
method.into(),
params,
attachments,
op_id,
)
.await?;
before_confirm(prepared.reference().get().to_owned())
.await
.map_err(RemoteClientError::HostRejected)?;
let reference: Value = serde_json::from_str(prepared.reference().get())?;
Ok((prepared, reference))
};
let prepare = async {
if let Some(deadline) = deadline {
tokio::time::timeout_at(deadline, prepare)
.await
.map_err(|_| {
RemoteClientError::HostRejected(
"Timed out preparing the Host mutation".into(),
)
})?
} else {
prepare.await
}
};
self.dispatch_prepared(
op_id,
prepare,
|(_, reference)| reference,
|(prepared, reference)| async move {
let confirm = prepared.confirm_with_reference(reference.clone(), on_progress);
if let Some(deadline) = deadline {
tokio::time::timeout_at(deadline, confirm)
.await
.unwrap_or_else(|cause| {
Err(RemoteClientError::MutationUncertain {
reference,
cause: Box::new(RemoteClientError::Io(std::io::Error::new(
std::io::ErrorKind::TimedOut,
cause,
))),
})
})
} else {
confirm.await
}
},
)
.await
}
async fn begin(
&self,
request: OperationRequest,
allow_create: bool,
) -> Result<JournalDispatch, RemoteClientError> {
if request.op_id.is_nil() {
return Err(RemoteClientError::Protocol(
"operation ID must not be nil".into(),
));
}
self.journal.begin(request, allow_create).await
}
async fn dispatch_mutation(
&self,
transport: &dyn RootTransport,
op_id: Uuid,
endpoint: &str,
method: &str,
params: Value,
) -> Result<Value, RemoteClientError> {
self.dispatch_prepared(
op_id,
transport.prepare_mutation(op_id, endpoint, method, params),
|prepared| prepared.reference(),
|prepared| prepared.confirm(),
)
.await
}
async fn dispatch_prepared<P, F>(
&self,
op_id: Uuid,
prepare: impl Future<Output = Result<P, RemoteClientError>>,
reference: impl FnOnce(&P) -> &Value,
confirm: impl FnOnce(P) -> F,
) -> Result<Value, RemoteClientError>
where
F: Future<Output = Result<Value, RemoteClientError>>,
{
let result = async {
let prepared = match prepare.await {
Ok(prepared) => prepared,
Err(RemoteClientError::HostRejected(diagnostic)) => {
return self
.journal
.record_receipt(
op_id,
OperationReceipt::Rejected(diagnostic),
ReceiptSource::PrepareRejection,
)
.await;
}
Err(error) => return Err(error),
};
if let Some(receipt) = self
.journal
.bind_reference(op_id, reference(&prepared))
.await?
{
return Ok(receipt);
}
let receipt = OperationReceipt::from_result(confirm(prepared).await)?;
self.journal
.record_receipt(op_id, receipt, ReceiptSource::Host)
.await
}
.await;
match result {
Ok(receipt) => receipt.into_result(),
Err(error) => {
// Terminal receipts win over a concurrent caller's uncertain result.
match self.journal.mark_uncertain(op_id).await? {
Some(receipt) => receipt.into_result(),
None => Err(error),
}
}
}
}
/// Read the original receipt through an explicitly authorized Host
/// receipt-reader endpoint. If the Host has no receipt, prepare the same
/// operation and verify its original reference before confirming it.
pub async fn reconcile(
&self,
root_id: &RootId,
op_id: Uuid,
receipt_endpoint: &str,
) -> Result<Value, RemoteClientError> {
self.reconcile_with(root_id, op_id, receipt_endpoint, true, None)
.await
}
/// Reconcile on the supplied admission, optionally limiting recovery to
/// reading a receipt for a request with ephemeral attachments.
pub async fn reconcile_remote(
&self,
calls: &RemoteCallHandle,
op_id: Uuid,
receipt_endpoint: &str,
replay: bool,
) -> Result<Value, RemoteClientError> {
let root_id = calls
.root_id()
.parse()
.map_err(|error: crate::InvalidRootId| {
RemoteClientError::Protocol(error.to_string())
})?;
self.reconcile_with(&root_id, op_id, receipt_endpoint, replay, Some(calls))
.await
}
async fn reconcile_with(
&self,
root_id: &RootId,
op_id: Uuid,
receipt_endpoint: &str,
replay: bool,
pinned: Option<&dyn RootTransport>,
) -> Result<Value, RemoteClientError> {
let operation = self
.journal
.get(op_id)
.await?
.filter(|op| &op.root_id == root_id)
.ok_or_else(|| RemoteClientError::UnknownOperation {
root_id: root_id.clone(),
op_id,
})?;
if let Some(receipt) = operation.receipt_json {
let receipt: OperationReceipt =
tokio::task::spawn_blocking(move || serde_json::from_str(&receipt)).await??;
return receipt.into_result();
}
let registered;
let transport = match pinned {
Some(transport) => transport,
None => {
registered = self.get(root_id)?;
registered.as_ref()
}
};
if let Some(reference) = operation.reference_json {
let reference: Value = serde_json::from_str(&reference)?;
let reply = transport
.call(receipt_endpoint, "read", reference.clone())
.await?;
if reply.get("reference") != Some(&reference) {
return Err(RemoteClientError::OperationReferenceChanged(op_id));
}
if reply["receipt"]["kind"] != "not_recorded" {
let receipt = OperationReceipt::from_result(mutation_reply_result(reply, None))?;
return self
.journal
.record_receipt(op_id, receipt, ReceiptSource::Host)
.await?
.into_result();
}
if operation.unconfirmed_receipt_json.is_some() {
return Err(RemoteClientError::OperationNeedsReconciliation(op_id));
}
}
if !replay {
return Err(RemoteClientError::OperationNeedsReconciliation(op_id));
}
let payload = operation.payload_json;
let params = tokio::task::spawn_blocking(move || serde_json::from_str(&payload)).await??;
self.dispatch_mutation(
transport,
op_id,
&operation.endpoint,
&operation.method,
params,
)
.await
}
}