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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
//! 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 scalar;
mod seed_dict;
mod sum_dict;

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

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

use futures::future::poll_fn;
use tower::Service;

use crate::state_machine::coordinator::RoundParameters;

/// 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(&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(&self) -> Result<MaskLengthResponse, FetchError>;

    /// Fetch the scalar used for aggregation for the current
    /// round. The update participants need this value to mask the
    /// model they trained.
    async fn scalar(&self) -> Result<ScalarResponse, FetchError>;

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

    /// Fetch the global seed dictionary. Each sum2 participant needs a
    /// different portion of that dictionary.
    async fn seed_dict(&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(&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, Scalar, Model> Fetcher
    for FetcherService<RoundParams, SumDict, SeedDict, MaskLength, Scalar, Model>
where
    Self: Clone
        + Send
        + Sync
        + 'static
        + Service<RoundParamsRequest, Response = RoundParameters>
        + Service<MaskLengthRequest, Response = MaskLengthResponse>
        + Service<ScalarRequest, Response = ScalarResponse>
        + Service<ModelRequest, Response = ModelResponse>
        + Service<SeedDictRequest, Response = SeedDictResponse>
        + Service<SumDictRequest, Response = SumDictResponse>,

    <Self as Service<RoundParamsRequest>>::Future: Send + Sync + 'static,
    <Self as Service<RoundParamsRequest>>::Error:
        Into<Box<dyn ::std::error::Error + 'static + Sync + Send>>,

    <Self as Service<MaskLengthRequest>>::Future: Send + Sync + 'static,
    <Self as Service<MaskLengthRequest>>::Error:
        Into<Box<dyn ::std::error::Error + 'static + Sync + Send>>,

    <Self as Service<ScalarRequest>>::Future: Send + Sync + 'static,
    <Self as Service<ScalarRequest>>::Error:
        Into<Box<dyn ::std::error::Error + 'static + Sync + Send>>,

    <Self as Service<ModelRequest>>::Future: Send + Sync + 'static,
    <Self as Service<ModelRequest>>::Error:
        Into<Box<dyn ::std::error::Error + 'static + Sync + Send>>,

    <Self as Service<SeedDictRequest>>::Future: Send + Sync + 'static,
    <Self as Service<SeedDictRequest>>::Error:
        Into<Box<dyn ::std::error::Error + 'static + Sync + Send>>,

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

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

    async fn scalar(&self) -> Result<ScalarResponse, FetchError> {
        let mut svc = self.clone();
        poll_fn(|cx| <Self as Service<ScalarRequest>>::poll_ready(&mut svc, cx))
            .await
            .map_err(into_fetch_error)?;
        Ok(
            <Self as Service<ScalarRequest>>::call(&mut svc, ScalarRequest)
                .await
                .map_err(into_fetch_error)?,
        )
    }

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

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

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

/// A service for fetching PET data. It implements the [`Fetcher`] trait.
#[derive(Clone)]
pub struct FetcherService<RoundParams, SumDict, SeedDict, MaskLength, Scalar, Model> {
    round_params: RoundParams,
    sum_dict: SumDict,
    seed_dict: SeedDict,
    mask_length: MaskLength,
    scalar: Scalar,
    model: Model,
}

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

impl<RoundParams, SumDict, SeedDict, MaskLength, Scalar, Model> Service<SumDictRequest>
    for FetcherService<RoundParams, SumDict, SeedDict, MaskLength, Scalar, Model>
where
    SumDict: Service<SumDictRequest>,
{
    type Response = <SumDict as Service<SumDictRequest>>::Response;
    type Error = <SumDict as Service<SumDictRequest>>::Error;
    type Future = <SumDict as Service<SumDictRequest>>::Future;

    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        <SumDict as Service<SumDictRequest>>::poll_ready(&mut self.sum_dict, cx)
    }

    fn call(&mut self, req: SumDictRequest) -> Self::Future {
        <SumDict as Service<SumDictRequest>>::call(&mut self.sum_dict, req)
    }
}

impl<RoundParams, SumDict, SeedDict, MaskLength, Scalar, Model> Service<SeedDictRequest>
    for FetcherService<RoundParams, SumDict, SeedDict, MaskLength, Scalar, Model>
where
    SeedDict: Service<SeedDictRequest>,
{
    type Response = <SeedDict as Service<SeedDictRequest>>::Response;
    type Error = <SeedDict as Service<SeedDictRequest>>::Error;
    type Future = <SeedDict as Service<SeedDictRequest>>::Future;

    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        <SeedDict as Service<SeedDictRequest>>::poll_ready(&mut self.seed_dict, cx)
    }

    fn call(&mut self, req: SeedDictRequest) -> Self::Future {
        <SeedDict as Service<SeedDictRequest>>::call(&mut self.seed_dict, req)
    }
}

impl<RoundParams, SumDict, SeedDict, MaskLength, Scalar, Model> Service<RoundParamsRequest>
    for FetcherService<RoundParams, SumDict, SeedDict, MaskLength, Scalar, Model>
where
    RoundParams: Service<RoundParamsRequest>,
{
    type Response = <RoundParams as Service<RoundParamsRequest>>::Response;
    type Error = <RoundParams as Service<RoundParamsRequest>>::Error;
    type Future = <RoundParams as Service<RoundParamsRequest>>::Future;

    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        <RoundParams as Service<RoundParamsRequest>>::poll_ready(&mut self.round_params, cx)
    }

    fn call(&mut self, req: RoundParamsRequest) -> Self::Future {
        <RoundParams as Service<RoundParamsRequest>>::call(&mut self.round_params, req)
    }
}

impl<RoundParams, SumDict, SeedDict, MaskLength, Scalar, Model> Service<ScalarRequest>
    for FetcherService<RoundParams, SumDict, SeedDict, MaskLength, Scalar, Model>
where
    Scalar: Service<ScalarRequest>,
{
    type Response = <Scalar as Service<ScalarRequest>>::Response;
    type Error = <Scalar as Service<ScalarRequest>>::Error;
    type Future = <Scalar as Service<ScalarRequest>>::Future;

    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        <Scalar as Service<ScalarRequest>>::poll_ready(&mut self.scalar, cx)
    }

    fn call(&mut self, req: ScalarRequest) -> Self::Future {
        <Scalar as Service<ScalarRequest>>::call(&mut self.scalar, req)
    }
}

impl<RoundParams, SumDict, SeedDict, MaskLength, Scalar, Model> Service<ModelRequest>
    for FetcherService<RoundParams, SumDict, SeedDict, MaskLength, Scalar, Model>
where
    Model: Service<ModelRequest>,
{
    type Response = <Model as Service<ModelRequest>>::Response;
    type Error = <Model as Service<ModelRequest>>::Error;
    type Future = <Model as Service<ModelRequest>>::Future;

    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        <Model as Service<ModelRequest>>::poll_ready(&mut self.model, cx)
    }

    fn call(&mut self, req: ModelRequest) -> Self::Future {
        <Model as Service<ModelRequest>>::call(&mut self.model, req)
    }
}

impl<RoundParams, SumDict, SeedDict, MaskLength, Scalar, Model> Service<MaskLengthRequest>
    for FetcherService<RoundParams, SumDict, SeedDict, MaskLength, Scalar, Model>
where
    MaskLength: Service<MaskLengthRequest>,
{
    type Response = <MaskLength as Service<MaskLengthRequest>>::Response;
    type Error = <MaskLength as Service<MaskLengthRequest>>::Error;
    type Future = <MaskLength as Service<MaskLengthRequest>>::Future;

    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        <MaskLength as Service<MaskLengthRequest>>::poll_ready(&mut self.mask_length, cx)
    }

    fn call(&mut self, req: MaskLengthRequest) -> Self::Future {
        <MaskLength as Service<MaskLengthRequest>>::call(&mut self.mask_length, req)
    }
}