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
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------

// stateful_proxy is a wrapper layer around com api,
// making manipulating com simple.

use log::info;
use mssf_com::{
    FabricCommon::FabricRuntime::{
        IFabricPrimaryReplicator, IFabricReplicator, IFabricStatefulServiceReplica,
    },
    FABRIC_EPOCH,
};
use windows_core::{ComInterface, HSTRING};

use crate::IFabricStringResultToHString;

use super::{
    stateful::{PrimaryReplicator, Replicator, StatefulServicePartition, StatefulServiceReplica},
    stateful_types::{Epoch, OpenMode, ReplicaInfo, ReplicaSetConfig, ReplicaSetQuarumMode, Role},
};

pub struct StatefulServiceReplicaProxy {
    com_impl: IFabricStatefulServiceReplica,
}

impl StatefulServiceReplicaProxy {
    pub fn new(com_impl: IFabricStatefulServiceReplica) -> StatefulServiceReplicaProxy {
        StatefulServiceReplicaProxy { com_impl }
    }
}

impl StatefulServiceReplica for StatefulServiceReplicaProxy {
    async fn open(
        &self,
        openmode: OpenMode,
        partition: &StatefulServicePartition,
    ) -> windows::core::Result<impl PrimaryReplicator> {
        info!("StatefulServiceReplicaProxy::open with mode {:?}", openmode);
        // replicator address
        let (tx, rx) = tokio::sync::oneshot::channel();
        let callback = crate::sync::AwaitableCallback2::i_new(move |ctx| {
            let res = unsafe { self.com_impl.EndOpen(ctx) };
            if tx.send(res).is_err() {
                debug_assert!(false, "Receiver is dropped.");
            }
        });

        let _ = unsafe {
            self.com_impl
                .BeginOpen(openmode.into(), partition.get_com(), &callback)?
        };
        let rplctr = rx.await.unwrap()?;
        // TODO: cast without clone will cause access violation on AddRef in SF runtime.
        let p_rplctr: IFabricPrimaryReplicator = rplctr.clone().cast().unwrap(); // must work
                                                                                 // Replicator must impl primary replicator as well.
        let res = PrimaryReplicatorProxy::new(p_rplctr);
        Ok(res)
    }
    async fn change_role(&self, newrole: Role) -> ::windows_core::Result<HSTRING> {
        // replica address
        info!("StatefulServiceReplicaProxy::change_role {:?}", newrole);
        let (tx, rx) = tokio::sync::oneshot::channel();
        let callback = crate::sync::AwaitableCallback2::i_new(move |ctx| {
            let res = unsafe { self.com_impl.EndChangeRole(ctx) };
            if tx.send(res).is_err() {
                debug_assert!(false, "Receiver is dropped.");
            }
        });

        let _ = unsafe { self.com_impl.BeginChangeRole(newrole.into(), &callback)? };
        let addr = rx.await.unwrap()?;
        Ok(IFabricStringResultToHString(&addr))
    }
    async fn close(&self) -> windows::core::Result<()> {
        info!("StatefulServiceReplicaProxy::close");
        let (tx, rx) = tokio::sync::oneshot::channel();
        let callback = crate::sync::AwaitableCallback2::i_new(move |ctx| {
            let res = unsafe { self.com_impl.EndClose(ctx) };
            if tx.send(res).is_err() {
                debug_assert!(false, "Receiver is dropped.");
            }
        });

        let _ = unsafe { self.com_impl.BeginClose(&callback)? };
        rx.await.unwrap()?;
        Ok(())
    }
    fn abort(&self) {
        info!("StatefulServiceReplicaProxy::abort");
        unsafe { self.com_impl.Abort() }
    }
}

pub struct ReplicatorProxy {
    com_impl: IFabricReplicator,
}

impl ReplicatorProxy {
    fn new(com_impl: IFabricReplicator) -> ReplicatorProxy {
        ReplicatorProxy { com_impl }
    }
}

impl Replicator for ReplicatorProxy {
    async fn open(&self) -> ::windows_core::Result<HSTRING> {
        info!("ReplicatorProxy::open");
        // replicator address
        let (tx, rx) = tokio::sync::oneshot::channel();
        let callback = crate::sync::AwaitableCallback2::i_new(move |ctx| {
            let res = unsafe { self.com_impl.EndOpen(ctx) };
            if tx.send(res).is_err() {
                debug_assert!(false, "Receiver is dropped.");
            }
        });
        let _ = unsafe { self.com_impl.BeginOpen(&callback)? };
        let addr = rx.await.unwrap()?;
        Ok(IFabricStringResultToHString(&addr))
    }
    async fn close(&self) -> ::windows_core::Result<()> {
        info!("ReplicatorProxy::close");
        let (tx, rx) = tokio::sync::oneshot::channel();
        let callback = crate::sync::AwaitableCallback2::i_new(move |ctx| {
            let res = unsafe { self.com_impl.EndClose(ctx) };
            if tx.send(res).is_err() {
                debug_assert!(false, "Receiver is dropped.");
            }
        });
        let _ = unsafe { self.com_impl.BeginClose(&callback)? };
        rx.await.unwrap()
    }
    async fn change_role(&self, epoch: &Epoch, role: &Role) -> ::windows_core::Result<()> {
        info!("ReplicatorProxy::change_role");
        let (tx, rx) = tokio::sync::oneshot::channel();
        let callback = crate::sync::AwaitableCallback2::i_new(move |ctx| {
            let res = unsafe { self.com_impl.EndChangeRole(ctx) };
            if tx.send(res).is_err() {
                debug_assert!(false, "Receiver is dropped.");
            }
        });
        {
            let epoch2: FABRIC_EPOCH = epoch.clone().into();
            let _ = unsafe {
                self.com_impl
                    .BeginChangeRole(&epoch2, role.clone().into(), &callback)?
            };
        }
        rx.await.unwrap()
    }
    async fn update_epoch(&self, epoch: &Epoch) -> ::windows_core::Result<()> {
        info!("ReplicatorProxy::update_epoch");
        let (tx, rx) = tokio::sync::oneshot::channel();
        let callback = crate::sync::AwaitableCallback2::i_new(move |ctx| {
            let res = unsafe { self.com_impl.EndUpdateEpoch(ctx) };
            if tx.send(res).is_err() {
                debug_assert!(false, "Receiver is dropped.");
            }
        });
        {
            let epoch2: FABRIC_EPOCH = epoch.clone().into();
            let _ = unsafe { self.com_impl.BeginUpdateEpoch(&epoch2, &callback)? };
        }
        rx.await.unwrap()
    }
    fn get_current_progress(&self) -> ::windows_core::Result<i64> {
        info!("ReplicatorProxy::get_current_progress");
        unsafe { self.com_impl.GetCurrentProgress() }
    }
    fn get_catch_up_capability(&self) -> ::windows_core::Result<i64> {
        info!("ReplicatorProxy::get_catch_up_capability");
        unsafe { self.com_impl.GetCatchUpCapability() }
    }
    fn abort(&self) {
        info!("ReplicatorProxy::abort");
        unsafe { self.com_impl.Abort() }
    }
}

pub struct PrimaryReplicatorProxy {
    com_impl: IFabricPrimaryReplicator,
    parent: ReplicatorProxy,
}

impl PrimaryReplicatorProxy {
    pub fn new(com_impl: IFabricPrimaryReplicator) -> PrimaryReplicatorProxy {
        let parent = ReplicatorProxy::new(com_impl.clone().cast().unwrap());
        PrimaryReplicatorProxy { com_impl, parent }
    }
}

impl Replicator for PrimaryReplicatorProxy {
    async fn open(&self) -> ::windows_core::Result<HSTRING> {
        self.parent.open().await
    }
    async fn close(&self) -> ::windows_core::Result<()> {
        self.parent.close().await
    }
    async fn change_role(&self, epoch: &Epoch, role: &Role) -> ::windows_core::Result<()> {
        self.parent.change_role(epoch, role).await
    }
    async fn update_epoch(&self, epoch: &Epoch) -> ::windows_core::Result<()> {
        self.parent.update_epoch(epoch).await
    }
    fn get_current_progress(&self) -> ::windows_core::Result<i64> {
        self.parent.get_current_progress()
    }
    fn get_catch_up_capability(&self) -> ::windows_core::Result<i64> {
        self.parent.get_catch_up_capability()
    }
    fn abort(&self) {
        self.parent.abort()
    }
}

impl PrimaryReplicator for PrimaryReplicatorProxy {
    async fn on_data_loss(&self) -> ::windows_core::Result<u8> {
        info!("PrimaryReplicatorProxy::on_data_loss");
        let (tx, rx) = tokio::sync::oneshot::channel();
        let callback = crate::sync::AwaitableCallback2::i_new(move |ctx| {
            let res = unsafe { self.com_impl.EndOnDataLoss(ctx) };
            if tx.send(res).is_err() {
                debug_assert!(false, "Receiver is dropped.");
            }
        });
        {
            let _ = unsafe { self.com_impl.BeginOnDataLoss(&callback)? };
        }
        rx.await.unwrap()
    }
    fn update_catch_up_replica_set_configuration(
        &self,
        currentconfiguration: &ReplicaSetConfig,
        previousconfiguration: &ReplicaSetConfig,
    ) -> ::windows_core::Result<()> {
        info!("PrimaryReplicatorProxy::update_catch_up_replica_set_configuration");
        let cc = currentconfiguration.get_raw();
        let pc = previousconfiguration.get_raw();
        unsafe { self.com_impl.UpdateCatchUpReplicaSetConfiguration(&cc, &pc) }
    }
    async fn wait_for_catch_up_quorum(
        &self,
        catchupmode: ReplicaSetQuarumMode,
    ) -> ::windows_core::Result<()> {
        info!("PrimaryReplicatorProxy::wait_for_catch_up_quorum");
        let (tx, rx) = tokio::sync::oneshot::channel();
        let callback = crate::sync::AwaitableCallback2::i_new(move |ctx| {
            let res = unsafe { self.com_impl.EndWaitForCatchUpQuorum(ctx) };
            if tx.send(res).is_err() {
                debug_assert!(false, "Receiver is dropped.");
            }
        });
        {
            let _ = unsafe {
                self.com_impl
                    .BeginWaitForCatchUpQuorum(catchupmode.into(), &callback)?
            };
        }
        rx.await.unwrap()
    }
    fn update_current_replica_set_configuration(
        &self,
        currentconfiguration: &ReplicaSetConfig,
    ) -> ::windows_core::Result<()> {
        info!("PrimaryReplicatorProxy::update_current_replica_set_configuration");
        unsafe {
            self.com_impl
                .UpdateCurrentReplicaSetConfiguration(&currentconfiguration.get_raw())
        }
    }
    async fn build_replica(&self, replica: &ReplicaInfo) -> ::windows_core::Result<()> {
        info!("PrimaryReplicatorProxy::build_replica");
        let (tx, rx) = tokio::sync::oneshot::channel();
        let callback = crate::sync::AwaitableCallback2::i_new(move |ctx| {
            let res = unsafe { self.com_impl.EndBuildReplica(ctx) };
            if tx.send(res).is_err() {
                debug_assert!(false, "Receiver is dropped.");
            }
        });
        {
            let _ = unsafe {
                self.com_impl
                    .BeginBuildReplica(&replica.get_raw(), &callback)?
            };
        }
        rx.await.unwrap()
    }
    fn remove_replica(&self, replicaid: i64) -> ::windows_core::Result<()> {
        info!("PrimaryReplicatorProxy::remove_replica");
        unsafe { self.com_impl.RemoveReplica(replicaid) }
    }
}