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
/********************************************************************************
 * Copyright (c) 2024 Contributors to the Eclipse Foundation
 *
 * See the NOTICE file(s) distributed with this work for additional
 * information regarding copyright ownership.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Apache License Version 2.0 which is available at
 * https://www.apache.org/licenses/LICENSE-2.0
 *
 * SPDX-License-Identifier: Apache-2.0
 ********************************************************************************/

use std::sync::Arc;
use thiserror::Error;

use async_trait::async_trait;
#[cfg(test)]
use mockall::automock;
use protobuf::MessageFull;

use crate::communication::RegistrationError;
use crate::{UCode, UStatus, UUri};

use super::{CallOptions, UPayload};

/// An error indicating a problem with invoking a (remote) service operation.
#[derive(Clone, Error, Debug)]
pub enum ServiceInvocationError {
    /// Indicates that the calling uE requested to add/create something that already exists.
    #[error("entity already exists: {0}")]
    AlreadyExists(String),
    /// Indicates that a request's time-to-live (TTL) has expired.
    ///
    /// Note that this only means that the reply to the request has not been received in time. The request
    /// may still have been processed by the (remote) service provider.
    #[error("request timed out")]
    DeadlineExceeded,
    /// Indicates that the service provider is in a state that prevents it from handling the request.
    #[error("failed precondition: {0}")]
    FailedPrecondition(String),
    /// Indicates that a serious but unspeciified internal error has occurred while sending/processing the request.
    #[error("internal error: {0}")]
    Internal(String),
    /// Indicates that the request cannot be processed because some of its parameters are invalid, e.g. not properly formatted.
    #[error("invalid argument: {0}")]
    InvalidArgument(String),
    /// Indicates that the requested entity was not found.
    #[error("no such entity: {0}")]
    NotFound(String),
    /// Indicates that the calling uE is authenticated but does not have the required authority to invoke the method.
    #[error("permission denied: {0}")]
    PermissionDenied(String),
    /// Indicates that some of the resources required for processing the request have been exhausted, e.g. disk space, number of API calls.
    #[error("resource exhausted: {0}")]
    ResourceExhausted(String),
    /// Indicates an unspecific error that occurred at the Transport Layer while trying to publish a message.
    #[error("unknown error: {0}")]
    RpcError(UStatus),
    /// Indicates that the calling uE could not be authenticated properly.
    #[error("unauthenticated")]
    Unauthenticated,
    /// Indicates that some of the resources required for processing the request are currently unavailable.
    #[error("resource unavailable: {0}")]
    Unavailable(String),
    /// Indicates that part or all of the invoked operation has not been implemented yet.
    #[error("unimplemented: {0}")]
    Unimplemented(String),
}

impl From<UStatus> for ServiceInvocationError {
    fn from(value: UStatus) -> Self {
        match value.code.enum_value() {
            Ok(UCode::ALREADY_EXISTS) => ServiceInvocationError::AlreadyExists(value.get_message()),
            Ok(UCode::DEADLINE_EXCEEDED) => ServiceInvocationError::DeadlineExceeded,
            Ok(UCode::FAILED_PRECONDITION) => {
                ServiceInvocationError::FailedPrecondition(value.get_message())
            }
            Ok(UCode::INTERNAL) => ServiceInvocationError::Internal(value.get_message()),
            Ok(UCode::INVALID_ARGUMENT) => {
                ServiceInvocationError::InvalidArgument(value.get_message())
            }
            Ok(UCode::NOT_FOUND) => ServiceInvocationError::NotFound(value.get_message()),
            Ok(UCode::PERMISSION_DENIED) => {
                ServiceInvocationError::PermissionDenied(value.get_message())
            }
            Ok(UCode::RESOURCE_EXHAUSTED) => {
                ServiceInvocationError::ResourceExhausted(value.get_message())
            }
            Ok(UCode::UNAUTHENTICATED) => ServiceInvocationError::Unauthenticated,
            Ok(UCode::UNAVAILABLE) => ServiceInvocationError::Unavailable(value.get_message()),
            Ok(UCode::UNIMPLEMENTED) => ServiceInvocationError::Unimplemented(value.get_message()),
            _ => ServiceInvocationError::RpcError(value),
        }
    }
}

impl From<ServiceInvocationError> for UStatus {
    fn from(value: ServiceInvocationError) -> Self {
        match value {
            ServiceInvocationError::AlreadyExists(msg) => {
                UStatus::fail_with_code(UCode::ALREADY_EXISTS, msg)
            }
            ServiceInvocationError::DeadlineExceeded => {
                UStatus::fail_with_code(UCode::DEADLINE_EXCEEDED, "request timed out")
            }
            ServiceInvocationError::FailedPrecondition(msg) => {
                UStatus::fail_with_code(UCode::FAILED_PRECONDITION, msg)
            }
            ServiceInvocationError::Internal(msg) => UStatus::fail_with_code(UCode::INTERNAL, msg),
            ServiceInvocationError::InvalidArgument(msg) => {
                UStatus::fail_with_code(UCode::INVALID_ARGUMENT, msg)
            }
            ServiceInvocationError::NotFound(msg) => UStatus::fail_with_code(UCode::NOT_FOUND, msg),
            ServiceInvocationError::PermissionDenied(msg) => {
                UStatus::fail_with_code(UCode::PERMISSION_DENIED, msg)
            }
            ServiceInvocationError::ResourceExhausted(msg) => {
                UStatus::fail_with_code(UCode::RESOURCE_EXHAUSTED, msg)
            }
            ServiceInvocationError::Unauthenticated => {
                UStatus::fail_with_code(UCode::UNAUTHENTICATED, "client must authenticate")
            }
            ServiceInvocationError::Unavailable(msg) => {
                UStatus::fail_with_code(UCode::UNAVAILABLE, msg)
            }
            ServiceInvocationError::Unimplemented(msg) => {
                UStatus::fail_with_code(UCode::UNIMPLEMENTED, msg)
            }
            _ => UStatus::fail_with_code(UCode::UNKNOWN, "unknown"),
        }
    }
}

/// A client for performing Remote Procedure Calls (RPC) on (other) uEntities.
///
/// Please refer to the
/// [Communication Layer API specification](https://github.com/eclipse-uprotocol/up-spec/blob/main/up-l2/api.adoc)
/// for details.
#[cfg_attr(test, automock)]
#[async_trait]
pub trait RpcClient: Send + Sync {
    /// Invokes a method on a service.
    ///
    /// # Arguments
    ///
    /// * `method` - The URI representing the method to invoke.
    /// * `call_options` - Options to include in the request message.
    /// * `payload` - The (optional) payload to include in the request message.
    ///
    /// # Returns
    ///
    /// The payload returned by the service operation.
    ///
    /// # Errors
    ///
    /// Returns an error if invocation fails or the given arguments cannot be turned into a valid RPC Request message.
    async fn invoke_method(
        &self,
        method: UUri,
        call_options: CallOptions,
        payload: Option<UPayload>,
    ) -> Result<Option<UPayload>, ServiceInvocationError>;
}

impl dyn RpcClient {
    /// Invokes a method on a service using and returning proto-generated `Message` objects.
    ///
    /// # Arguments
    ///
    /// * `method` - The URI representing the method to invoke.
    /// * `call_options` - Options to include in the request message.
    /// * `proto_message` - The protobuf `Message` to include in the request message.
    ///
    /// # Returns
    ///
    /// The payload returned by the service operation as a protobuf `Message`.
    ///
    /// # Errors
    ///
    /// Returns an error if invocation fails, the given arguments cannot be turned into a valid RPC Request message,
    /// result protobuf deserialization fails, or result payload is empty.
    pub async fn invoke_proto_method<T, R>(
        &self,
        method: UUri,
        call_options: CallOptions,
        proto_message: T,
    ) -> Result<R, ServiceInvocationError>
    where
        T: MessageFull,
        R: MessageFull,
    {
        let payload = UPayload::try_from_protobuf(proto_message)
            .map_err(|e| ServiceInvocationError::InvalidArgument(e.to_string()))?;

        let result = self
            .invoke_method(method, call_options, Some(payload))
            .await?;

        if let Some(result) = result {
            UPayload::extract_protobuf::<R>(&result)
                .map_err(|e| ServiceInvocationError::InvalidArgument(e.to_string()))
        } else {
            Err(ServiceInvocationError::InvalidArgument(
                "No payload".to_string(),
            ))
        }
    }
}

/// A handler for processing incoming RPC requests.
///
#[cfg_attr(test, automock)]
#[async_trait]
pub trait RequestHandler: Send + Sync {
    /// Invokes a method with given input parameters.
    ///
    /// Implementations MUST NOT block the calling thread. Long running
    /// computations should be performed on a separate worker thread, yielding
    /// on the calling thread.
    ///
    /// # Arguments
    ///
    /// * `resource_id` - The resource identifier of the method to invoke.
    /// * `request_payload` - The raw payload that contains the input data for the method.
    ///
    /// # Returns
    ///
    /// the output data generated by the method.
    ///
    /// # Errors
    ///
    /// Returns an error if the method request could not be processed successfully.
    async fn invoke_method(
        &self,
        resource_id: u16,
        request_payload: Option<UPayload>,
    ) -> Result<Option<UPayload>, ServiceInvocationError>;
}

/// A server for exposing Remote Procedure Call (RPC) endpoints.
///
/// Please refer to the
/// [Communication Layer API specification](https://github.com/eclipse-uprotocol/up-spec/blob/main/up-l2/api.adoc)
/// for details.
#[async_trait]
pub trait RpcServer {
    /// Registers an endpoint for RPC requests.
    ///
    /// Note that only a single endpoint can be registered for a given resource ID.
    /// However, the same request handler can be registered for multiple endpoints.
    ///
    /// # Arguments
    ///
    /// * `origin_filter` - A pattern defining origin addresses to accept requests from. If `None`, requests
    ///                     will be accepted from all sources.
    /// * `resource_id` - The resource identifier of the (local) method to accept requests for.
    /// * `request_handler` - The handler to invoke for each incoming request.
    ///
    /// # Errors
    ///
    /// Returns an error if the listener cannot be registered or if a listener has already been registered
    /// for the given resource ID.
    async fn register_endpoint(
        &self,
        origin_filter: Option<&UUri>,
        resource_id: u16,
        request_handler: Arc<dyn RequestHandler>,
    ) -> Result<(), RegistrationError>;

    /// Unregisters a previously [registered endpoint](Self::register_endpoint).
    ///
    /// # Arguments
    ///
    /// * `origin_filter` - The origin pattern that the endpoint had been registered for.
    /// * `resource_id` - The (local) resource identifier that the endpoint had been registered for.
    /// * `request_handler` - The handler to unregister.
    ///
    /// # Errors
    ///
    /// Returns an error if the listener cannot be unregistered.
    async fn unregister_endpoint(
        &self,
        origin_filter: Option<&UUri>,
        resource_id: u16,
        request_handler: Arc<dyn RequestHandler>,
    ) -> Result<(), RegistrationError>;
}