aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/csharp/Grpc.Examples/MathServiceImpl.cs
blob: 85b5e2dd96b8098051156705bd0cd74cb6323123 (plain)
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
#region Copyright notice and license

// Copyright 2015-2016 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#endregion

using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Grpc.Core;
using Grpc.Core.Utils;

namespace Math
{
    /// <summary>
    /// Implementation of MathService server
    /// </summary>
    public class MathServiceImpl : Math.MathBase
    {
        public override Task<DivReply> Div(DivArgs request, ServerCallContext context)
        {
            return Task.FromResult(DivInternal(request));
        }

        public override async Task Fib(FibArgs request, IServerStreamWriter<Num> responseStream, ServerCallContext context)
        {
            var limit = request.Limit > 0 ? request.Limit : long.MaxValue;
            var fibEnumerator = FibInternal(limit).GetEnumerator();

            // Keep streaming the sequence until the call is cancelled.
            // Use CancellationToken from ServerCallContext to detect the cancellation.
            while (!context.CancellationToken.IsCancellationRequested && fibEnumerator.MoveNext())
            {
                await responseStream.WriteAsync(fibEnumerator.Current);
                await Task.Delay(100);
            }
        }

        public override async Task<Num> Sum(IAsyncStreamReader<Num> requestStream, ServerCallContext context)
        {
            long sum = 0;
            await requestStream.ForEachAsync(async num =>
            {
                sum += num.Num_;
            });
            return new Num { Num_ = sum };
        }

        public override async Task DivMany(IAsyncStreamReader<DivArgs> requestStream, IServerStreamWriter<DivReply> responseStream, ServerCallContext context)
        {
            await requestStream.ForEachAsync(async divArgs => await responseStream.WriteAsync(DivInternal(divArgs)));
        }

        static DivReply DivInternal(DivArgs args)
        {
            if (args.Divisor == 0)
            {
                // One can finish the RPC with non-ok status by throwing RpcException instance.
                // Alternatively, resulting status can be set using ServerCallContext.Status
                throw new RpcException(new Status(StatusCode.InvalidArgument, "Division by zero"));
            }

            long quotient = args.Dividend / args.Divisor;
            long remainder = args.Dividend % args.Divisor;
            return new DivReply { Quotient = quotient, Remainder = remainder };
        }

        static IEnumerable<Num> FibInternal(long n)
        {
            long a = 1;
            yield return new Num { Num_ = a };

            long b = 1;
            for (long i = 0; i < n - 1; i++)
            {
                long temp = a;
                a = b;
                b = temp + b;
                yield return new Num { Num_ = a };
            }
        }        
    }
}