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
//! This module provides the services for serving data.
//!
//! There are multiple such services and the [`Fetcher`] trait
//! provides a single unifying interface for all of these.
mod mask_length;
mod model;
mod round_parameters;
mod seed_dict;
mod sum_dict;

pub use self::{
    mask_length::{MaskLengthRequest, MaskLengthResponse, MaskLengthService},
    model::{ModelRequest, ModelResponse, ModelService},
    round_parameters::{RoundParamsRequest, RoundParamsResponse, RoundParamsService},
    seed_dict::{SeedDictRequest, SeedDictResponse, SeedDictService},
    sum_dict::{SumDictRequest, SumDictResponse, SumDictService},
};

use std::task::{Context, Poll};

use futures::future::poll_fn;
use tower::{layer::Layer, Service, ServiceBuilder};

use crate::state_machine::events::EventSubscriber;

/// A single interface for retrieving data from the coordinator.
#[async_trait]
pub trait Fetcher {
    /// Fetch the parameters for the current round
    async fn round_params(&mut self) -> Result<RoundParamsResponse, FetchError>;

    /// Fetch the mask length for the current round. The sum
    /// participants need this value during the sum2 phase to derive
    /// masks from the update participant's masking seeds.
    async fn mask_length(&mut self) -> Result<MaskLengthResponse, FetchError>;

    /// Fetch the latest global model.
    async fn model(&mut self) -> Result<ModelResponse, FetchError>;

    /// Fetch the global seed dictionary. Each sum2 participant needs a
    /// different portion of that dictionary.
    async fn seed_dict(&mut self) -> Result<SeedDictResponse, FetchError>;

    /// Fetch the sum dictionary. The update participants need this
    /// dictionary to encrypt their masking seed for each sum
    /// participant.
    async fn sum_dict(&mut self) -> Result<SumDictResponse, FetchError>;
}

/// An error returned by the [`Fetcher`]'s method.
pub type FetchError = anyhow::Error;

fn into_fetch_error<E: Into<Box<dyn ::std::error::Error + 'static + Sync + Send>>>(
    e: E,
) -> FetchError {
    anyhow::anyhow!("Fetcher failed: {:?}", e.into())
}

#[async_trait]
impl<RoundParams, SumDict, SeedDict, MaskLength, Model> Fetcher
    for Fetchers<RoundParams, SumDict, SeedDict, MaskLength, Model>
where
    Self: Send + Sync + 'static,

    RoundParams: Service<RoundParamsRequest, Response = RoundParamsResponse> + Send + 'static,
    <RoundParams as Service<RoundParamsRequest>>::Future: Send + Sync + 'static,
    <RoundParams as Service<RoundParamsRequest>>::Error:
        Into<Box<dyn ::std::error::Error + 'static + Sync + Send>>,

    MaskLength: Service<MaskLengthRequest, Response = MaskLengthResponse> + Send + 'static,
    <MaskLength as Service<MaskLengthRequest>>::Future: Send + Sync + 'static,
    <MaskLength as Service<MaskLengthRequest>>::Error:
        Into<Box<dyn ::std::error::Error + 'static + Sync + Send>>,

    Model: Service<ModelRequest, Response = ModelResponse> + Send + 'static,
    <Model as Service<ModelRequest>>::Future: Send + Sync + 'static,
    <Model as Service<ModelRequest>>::Error:
        Into<Box<dyn ::std::error::Error + 'static + Sync + Send>>,

    SeedDict: Service<SeedDictRequest, Response = SeedDictResponse> + Send + 'static,
    <SeedDict as Service<SeedDictRequest>>::Future: Send + Sync + 'static,
    <SeedDict as Service<SeedDictRequest>>::Error:
        Into<Box<dyn ::std::error::Error + 'static + Sync + Send>>,

    SumDict: Service<SumDictRequest, Response = SumDictResponse> + Send + 'static,
    <SumDict as Service<SumDictRequest>>::Future: Send + Sync + 'static,
    <SumDict as Service<SumDictRequest>>::Error:
        Into<Box<dyn ::std::error::Error + 'static + Sync + Send>>,
{
    async fn round_params(&mut self) -> Result<RoundParamsResponse, FetchError> {
        poll_fn(|cx| {
            <RoundParams as Service<RoundParamsRequest>>::poll_ready(&mut self.round_params, cx)
        })
        .await
        .map_err(into_fetch_error)?;
        Ok(<RoundParams as Service<RoundParamsRequest>>::call(
            &mut self.round_params,
            RoundParamsRequest,
        )
        .await
        .map_err(into_fetch_error)?)
    }

    async fn mask_length(&mut self) -> Result<MaskLengthResponse, FetchError> {
        poll_fn(|cx| {
            <MaskLength as Service<MaskLengthRequest>>::poll_ready(&mut self.mask_length, cx)
        })
        .await
        .map_err(into_fetch_error)?;
        Ok(<MaskLength as Service<MaskLengthRequest>>::call(
            &mut self.mask_length,
            MaskLengthRequest,
        )
        .await
        .map_err(into_fetch_error)?)
    }

    async fn model(&mut self) -> Result<ModelResponse, FetchError> {
        poll_fn(|cx| <Model as Service<ModelRequest>>::poll_ready(&mut self.model, cx))
            .await
            .map_err(into_fetch_error)?;
        Ok(
            <Model as Service<ModelRequest>>::call(&mut self.model, ModelRequest)
                .await
                .map_err(into_fetch_error)?,
        )
    }

    async fn seed_dict(&mut self) -> Result<SeedDictResponse, FetchError> {
        poll_fn(|cx| <SeedDict as Service<SeedDictRequest>>::poll_ready(&mut self.seed_dict, cx))
            .await
            .map_err(into_fetch_error)?;
        Ok(
            <SeedDict as Service<SeedDictRequest>>::call(&mut self.seed_dict, SeedDictRequest)
                .await
                .map_err(into_fetch_error)?,
        )
    }

    async fn sum_dict(&mut self) -> Result<SumDictResponse, FetchError> {
        poll_fn(|cx| <SumDict as Service<SumDictRequest>>::poll_ready(&mut self.sum_dict, cx))
            .await
            .map_err(into_fetch_error)?;
        Ok(
            <SumDict as Service<SumDictRequest>>::call(&mut self.sum_dict, SumDictRequest)
                .await
                .map_err(into_fetch_error)?,
        )
    }
}

pub(in crate::services) struct FetcherService<S>(S);

impl<S, R> Service<R> for FetcherService<S>
where
    S: Service<R>,
{
    type Response = S::Response;
    type Error = S::Error;
    type Future = S::Future;

    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        self.0.poll_ready(cx)
    }

    fn call(&mut self, req: R) -> Self::Future {
        self.0.call(req)
    }
}

pub(in crate::services) struct FetcherLayer;

impl<S> Layer<S> for FetcherLayer {
    type Service = FetcherService<S>;

    fn layer(&self, service: S) -> Self::Service {
        FetcherService(service)
    }
}

#[derive(Debug, Clone)]
pub struct Fetchers<RoundParams, SumDict, SeedDict, MaskLength, Model> {
    round_params: RoundParams,
    sum_dict: SumDict,
    seed_dict: SeedDict,
    mask_length: MaskLength,
    model: Model,
}

impl<RoundParams, SumDict, SeedDict, MaskLength, Model>
    Fetchers<RoundParams, SumDict, SeedDict, MaskLength, Model>
{
    pub fn new(
        round_params: RoundParams,
        sum_dict: SumDict,
        seed_dict: SeedDict,
        mask_length: MaskLength,
        model: Model,
    ) -> Self {
        Self {
            round_params,
            sum_dict,
            seed_dict,
            mask_length,
            model,
        }
    }
}

/// Construct a [`Fetcher`] service
pub fn fetcher(event_subscriber: &EventSubscriber) -> impl Fetcher + Sync + Send + Clone + 'static {
    let round_params = ServiceBuilder::new()
        .buffer(100)
        .concurrency_limit(100)
        .layer(FetcherLayer)
        .service(RoundParamsService::new(event_subscriber));

    let mask_length = ServiceBuilder::new()
        .buffer(100)
        .concurrency_limit(100)
        .layer(FetcherLayer)
        .service(MaskLengthService::new(event_subscriber));

    let model = ServiceBuilder::new()
        .buffer(100)
        .concurrency_limit(100)
        .layer(FetcherLayer)
        .service(ModelService::new(event_subscriber));

    let sum_dict = ServiceBuilder::new()
        .buffer(100)
        .concurrency_limit(100)
        .layer(FetcherLayer)
        .service(SumDictService::new(event_subscriber));

    let seed_dict = ServiceBuilder::new()
        .buffer(100)
        .concurrency_limit(100)
        .layer(FetcherLayer)
        .service(SeedDictService::new(event_subscriber));

    Fetchers::new(round_params, sum_dict, seed_dict, mask_length, model)
}