shors 0.13.0

Transport layer for cartridge + tarantool-module projects.
Documentation
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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
use crate::tarantool::tlua::{AnyLuaString, CallError, LuaThread};
use crate::tarantool::tuple::Tuple;
use crate::tlua;
use crate::transport::Context;
use serde::Serialize;
use std::fmt::Debug;
use std::ops::Deref;
use std::time::Duration;
use thiserror::Error;

#[derive(Error, Debug)]
pub enum RemoteCallError {
    #[error("remote call: {0}")]
    RemoteCallError(String),
    #[error("prepare request: {0}")]
    PrepareRequestError(#[from] rmp_serde::encode::Error),
}

pub struct Builder<'a> {
    tlua: &'a LuaThread,
    handler_name: String,
}

impl<'a> Builder<'a> {
    const DEFAULT_HANDLER: &'static str = "rpc_handler";

    pub fn new(tlua: &'a LuaThread) -> Self {
        Self {
            tlua,
            handler_name: Self::DEFAULT_HANDLER.to_string(),
        }
    }

    pub fn with_custom_handler(tlua: &'a LuaThread, handler: &'static str) -> Self {
        Self {
            tlua,
            handler_name: handler.to_string(),
        }
    }

    /// Create endpoint routed by bucket_id.
    pub fn shard_endpoint<A: Serialize>(self, path: &'static str) -> ShardEndpoint<'a, A> {
        let f = move |ctx: &mut Context, bucket_id, path, opts, args| {
            let args = rmp_serde::to_vec_named(&args)?;
            let args = AnyLuaString(args);

            self.tlua
                .get::<tlua::LuaFunction<_>, _>("call_shard")
                .ok_or_else(|| RemoteCallError::RemoteCallError("call_shard: not found".into()))?
                .call_with_args(&(
                    &self.handler_name,
                    bucket_id,
                    opts,
                    (path, ctx.clone(), args),
                ))
                .map_err(map_lua_fn_err)
        };

        ShardEndpoint {
            timeout: Duration::from_secs(10),
            vshard_group: "default",
            route: path,
            balance: false,
            handler: RemoteLuaCall(Box::new(f)),
        }
    }

    /// Create async endpoint routed by bucket_id.
    pub fn async_shard_endpoint<A: Serialize>(
        self,
        path: &'static str,
    ) -> AsyncShardEndpoint<'a, A> {
        let f = move |ctx: &mut Context, bucket_id, path, opts, args| {
            let args = rmp_serde::to_vec_named(&args)?;
            let args = AnyLuaString(args);

            self.tlua
                .get::<tlua::LuaFunction<_>, _>("call_shard_async")
                .ok_or_else(|| {
                    RemoteCallError::RemoteCallError("call_shard_async: not found".into())
                })?
                .call_with_args(&(
                    &self.handler_name,
                    bucket_id,
                    opts,
                    (path, ctx.clone(), args),
                ))
                .map_err(map_lua_fn_err)
        };

        AsyncShardEndpoint {
            timeout: Duration::from_secs(10),
            vshard_group: "default",
            route: path,
            balance: false,
            handler: RemoteLuaCall(Box::new(f)),
        }
    }

    /// Create endpoint routed by instance uuid.
    pub fn replicaset_endpoint<A: Serialize>(
        self,
        path: &'static str,
    ) -> ReplicasetEndpoint<'a, A> {
        let f = move |ctx: &mut Context, rs_uuid, path, opts, args| {
            let args = rmp_serde::to_vec_named(&args)?;
            let args = AnyLuaString(args);

            self.tlua
                .get::<tlua::LuaFunction<_>, _>("call_rs")
                .ok_or_else(|| RemoteCallError::RemoteCallError("call_rs: not found".into()))?
                .call_with_args(&(&self.handler_name, rs_uuid, opts, (path, ctx.clone(), args)))
                .map_err(map_lua_fn_err)
        };

        ReplicasetEndpoint {
            timeout: Duration::from_secs(10),
            vshard_group: "default",
            prefer_replica: false,
            route: path,
            handler: RemoteLuaCall(Box::new(f)),
        }
    }

    /// Create endpoint routed by cartridge role.
    pub fn role_endpoint<A: Serialize>(
        self,
        role: &'static str,
        path: &'static str,
    ) -> RoleEndpoint<'a, A> {
        let f = move |ctx: &mut Context, _, path, opts, args| {
            let args = rmp_serde::to_vec_named(&args)?;
            let args = AnyLuaString(args);

            self.tlua
                .get::<tlua::LuaFunction<_>, _>("call_role")
                .ok_or_else(|| RemoteCallError::RemoteCallError("call_role: not found".into()))?
                .call_with_args(&(Self::DEFAULT_HANDLER, role, opts, (path, ctx.clone(), args)))
                .map_err(map_lua_fn_err)
        };

        RoleEndpoint {
            timeout: Duration::from_secs(10),
            route: path,
            route_mode: RouteMode::RandomMaster,
            handler: RemoteLuaCall(Box::new(f)),
        }
    }
}

// options using by lua function, note that the final lua implementation does not necessarily use all the fields
#[derive(Clone, tlua::Push, Default)]
pub struct Options {
    timeout: f64,
    vshard_group: &'static str,
    uri: Option<String>,
    leader_only: bool,
    prefer_replica: bool,
    balance: bool,
}

type RemoteLuaCallFn<'a, ID, A> =
    dyn Fn(&mut Context, ID, &'static str, Options, A) -> Result<Tuple, RemoteCallError> + 'a;
pub struct RemoteLuaCall<'a, ID, A: Serialize>(pub Box<RemoteLuaCallFn<'a, ID, A>>);

impl<'a, ID, A: Serialize> Deref for RemoteLuaCall<'a, ID, A> {
    type Target = Box<RemoteLuaCallFn<'a, ID, A>>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

type MiddlewareFn<'a, ID, A> = dyn Fn(RemoteLuaCall<'a, ID, A>) -> RemoteLuaCall<'a, ID, A>;
pub struct Middleware<'a, ID, A: Serialize>(pub Box<MiddlewareFn<'a, ID, A>>);

impl<'a, ID, A: Serialize> Deref for Middleware<'a, ID, A> {
    type Target = Box<MiddlewareFn<'a, ID, A>>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

/// Rpc endpoint routed by bucket_id.
pub struct ShardEndpoint<'a, A: Serialize> {
    timeout: Duration,
    vshard_group: &'static str,
    route: &'static str,
    balance: bool,
    handler: RemoteLuaCall<'a, i64, A>,
}

impl<'a, A: Serialize> ShardEndpoint<'a, A> {
    pub fn with_middleware(self, mw: Middleware<'a, i64, A>) -> Self {
        Self {
            handler: (mw)(self.handler),
            ..self
        }
    }

    pub fn with_vshard_group(self, group: &'static str) -> Self {
        Self {
            vshard_group: group,
            ..self
        }
    }

    pub fn with_balancer(self) -> Self {
        Self {
            balance: true,
            ..self
        }
    }

    pub fn with_timeout(self, timeout: Duration) -> Self {
        Self { timeout, ..self }
    }

    pub fn call(
        &self,
        context: &mut Context,
        bucket_id: i64,
        args: A,
    ) -> Result<Tuple, RemoteCallError> {
        context.put("path", self.route);
        (self.handler)(
            context,
            bucket_id,
            self.route,
            Options {
                timeout: self.timeout.as_secs_f64(),
                vshard_group: self.vshard_group,
                balance: self.balance,
                ..Default::default()
            },
            args,
        )
    }
}

/// Rpc endpoint routed by bucket_id. Rpc call execute in separate fiber.
pub struct AsyncShardEndpoint<'a, A: Serialize> {
    timeout: Duration,
    vshard_group: &'static str,
    route: &'static str,
    balance: bool,
    handler: RemoteLuaCall<'a, i64, A>,
}

impl<'a, A: Serialize> AsyncShardEndpoint<'a, A> {
    pub fn with_middleware(self, mw: Middleware<'a, i64, A>) -> Self {
        Self {
            handler: (mw)(self.handler),
            ..self
        }
    }

    pub fn with_vshard_group(self, group: &'static str) -> Self {
        Self {
            vshard_group: group,
            ..self
        }
    }

    pub fn with_balancer(self) -> Self {
        Self {
            balance: true,
            ..self
        }
    }

    pub fn with_timeout(self, timeout: Duration) -> Self {
        Self { timeout, ..self }
    }

    pub fn call(
        &self,
        context: &mut Context,
        bucket_id: i64,
        args: A,
    ) -> Result<(), RemoteCallError> {
        context.put("path", self.route);
        let opts = Options {
            timeout: self.timeout.as_secs_f64(),
            vshard_group: self.vshard_group,
            balance: self.balance,
            ..Default::default()
        };
        (self.handler)(context, bucket_id, self.route, opts, args).map(|_| ())
    }
}

/// Rpc endpoint routed by replicaset uuid.
pub struct ReplicasetEndpoint<'a, A: Serialize> {
    timeout: Duration,
    vshard_group: &'static str,
    prefer_replica: bool,
    route: &'static str,
    handler: RemoteLuaCall<'a, &'a str, A>,
}

impl<'a, A: Serialize> ReplicasetEndpoint<'a, A> {
    pub fn with_middleware(self, mw: Middleware<'a, &'a str, A>) -> Self {
        Self {
            handler: (mw)(self.handler),
            ..self
        }
    }

    pub fn with_vshard_group(self, group: &'static str) -> Self {
        Self {
            vshard_group: group,
            ..self
        }
    }

    pub fn with_timeout(self, timeout: Duration) -> Self {
        Self { timeout, ..self }
    }

    /// Call an endpoint with preference for a replica rather than a master
    pub fn prefer_replica(self) -> Self {
        Self {
            prefer_replica: true,
            ..self
        }
    }

    pub fn call(
        &self,
        context: &mut Context,
        rs_uuid: &'a str,
        args: A,
    ) -> Result<Tuple, RemoteCallError> {
        context.put("path", self.route);
        let opts = Options {
            timeout: self.timeout.as_secs_f64(),
            vshard_group: self.vshard_group,
            prefer_replica: self.prefer_replica,
            ..Default::default()
        };

        (self.handler)(context, rs_uuid, self.route, opts, args)
    }
}

/// Routing call mode
/// It need because cartridge rpc call has 2 different mode for calling rpc function.
#[derive(Default)]
enum RouteMode<'a> {
    /// This mode means route would be called on a suitable healthy instance with an enabled role
    #[default]
    RandomMaster,
    /// This mode means route would be called on the particular uri and it maybe not master
    CustomUri(&'a str),
}

/// Rpc endpoint routed by cartridge role.
/// By default perform a call only on the random replicaset leader.
/// Target role must export `rpc_handler` function.
pub struct RoleEndpoint<'a, A: Serialize> {
    timeout: Duration,
    route: &'static str,
    route_mode: RouteMode<'a>,
    handler: RemoteLuaCall<'a, (), A>,
}

impl<'a, A: Serialize> RoleEndpoint<'a, A> {
    pub fn with_middleware(self, mw: Middleware<'a, (), A>) -> Self {
        Self {
            handler: (mw)(self.handler),
            ..self
        }
    }

    pub fn with_timeout(self, timeout: Duration) -> Self {
        Self { timeout, ..self }
    }

    /// So cartridge API option `leader_only` and `uri` are not compatible,
    /// this method replace default behaviour (when prc was called on random replicaset
    /// master with option `leader_only`).
    /// Method do an rpc call to instance by uri, no metter is it replica or master.
    pub fn with_uri(self, uri: &'a str) -> Self {
        Self {
            route_mode: RouteMode::CustomUri(uri),
            ..self
        }
    }

    pub fn call(&self, context: &mut Context, args: A) -> Result<Tuple, RemoteCallError> {
        context.put("path", self.route);
        let mut opts = Options {
            timeout: self.timeout.as_secs_f64(),
            ..Default::default()
        };

        match self.route_mode {
            RouteMode::RandomMaster => opts.leader_only = true,
            RouteMode::CustomUri(uri) => opts.uri = Some(uri.to_string()),
        }

        (self.handler)(context, (), self.route, opts, args)
    }
}

fn map_lua_fn_err<E>(e: CallError<E>) -> RemoteCallError {
    match e {
        CallError::LuaError(e) => RemoteCallError::RemoteCallError(format!("{}", e)),
        CallError::PushError(_) => RemoteCallError::RemoteCallError("push error".into()),
    }
}