annotate src/capnproto-0.6.0/c++/samples/calculator-server.c++ @ 147:45360b968bf4

Cap'n Proto v0.6 + build for OSX
author Chris Cannam <cannam@all-day-breakfast.com>
date Mon, 22 May 2017 10:01:37 +0100
parents
children
rev   line source
cannam@147 1 // Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors
cannam@147 2 // Licensed under the MIT License:
cannam@147 3 //
cannam@147 4 // Permission is hereby granted, free of charge, to any person obtaining a copy
cannam@147 5 // of this software and associated documentation files (the "Software"), to deal
cannam@147 6 // in the Software without restriction, including without limitation the rights
cannam@147 7 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
cannam@147 8 // copies of the Software, and to permit persons to whom the Software is
cannam@147 9 // furnished to do so, subject to the following conditions:
cannam@147 10 //
cannam@147 11 // The above copyright notice and this permission notice shall be included in
cannam@147 12 // all copies or substantial portions of the Software.
cannam@147 13 //
cannam@147 14 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
cannam@147 15 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
cannam@147 16 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
cannam@147 17 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
cannam@147 18 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
cannam@147 19 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
cannam@147 20 // THE SOFTWARE.
cannam@147 21
cannam@147 22 #include "calculator.capnp.h"
cannam@147 23 #include <kj/debug.h>
cannam@147 24 #include <capnp/ez-rpc.h>
cannam@147 25 #include <capnp/message.h>
cannam@147 26 #include <iostream>
cannam@147 27
cannam@147 28 typedef unsigned int uint;
cannam@147 29
cannam@147 30 kj::Promise<double> readValue(Calculator::Value::Client value) {
cannam@147 31 // Helper function to asynchronously call read() on a Calculator::Value and
cannam@147 32 // return a promise for the result. (In the future, the generated code might
cannam@147 33 // include something like this automatically.)
cannam@147 34
cannam@147 35 return value.readRequest().send()
cannam@147 36 .then([](capnp::Response<Calculator::Value::ReadResults> result) {
cannam@147 37 return result.getValue();
cannam@147 38 });
cannam@147 39 }
cannam@147 40
cannam@147 41 kj::Promise<double> evaluateImpl(
cannam@147 42 Calculator::Expression::Reader expression,
cannam@147 43 capnp::List<double>::Reader params = capnp::List<double>::Reader()) {
cannam@147 44 // Implementation of CalculatorImpl::evaluate(), also shared by
cannam@147 45 // FunctionImpl::call(). In the latter case, `params` are the parameter
cannam@147 46 // values passed to the function; in the former case, `params` is just an
cannam@147 47 // empty list.
cannam@147 48
cannam@147 49 switch (expression.which()) {
cannam@147 50 case Calculator::Expression::LITERAL:
cannam@147 51 return expression.getLiteral();
cannam@147 52
cannam@147 53 case Calculator::Expression::PREVIOUS_RESULT:
cannam@147 54 return readValue(expression.getPreviousResult());
cannam@147 55
cannam@147 56 case Calculator::Expression::PARAMETER: {
cannam@147 57 KJ_REQUIRE(expression.getParameter() < params.size(),
cannam@147 58 "Parameter index out-of-range.");
cannam@147 59 return params[expression.getParameter()];
cannam@147 60 }
cannam@147 61
cannam@147 62 case Calculator::Expression::CALL: {
cannam@147 63 auto call = expression.getCall();
cannam@147 64 auto func = call.getFunction();
cannam@147 65
cannam@147 66 // Evaluate each parameter.
cannam@147 67 kj::Array<kj::Promise<double>> paramPromises =
cannam@147 68 KJ_MAP(param, call.getParams()) {
cannam@147 69 return evaluateImpl(param, params);
cannam@147 70 };
cannam@147 71
cannam@147 72 // Join the array of promises into a promise for an array.
cannam@147 73 kj::Promise<kj::Array<double>> joinedParams =
cannam@147 74 kj::joinPromises(kj::mv(paramPromises));
cannam@147 75
cannam@147 76 // When the parameters are complete, call the function.
cannam@147 77 return joinedParams.then([KJ_CPCAP(func)](kj::Array<double>&& paramValues) mutable {
cannam@147 78 auto request = func.callRequest();
cannam@147 79 request.setParams(paramValues);
cannam@147 80 return request.send().then(
cannam@147 81 [](capnp::Response<Calculator::Function::CallResults>&& result) {
cannam@147 82 return result.getValue();
cannam@147 83 });
cannam@147 84 });
cannam@147 85 }
cannam@147 86
cannam@147 87 default:
cannam@147 88 // Throw an exception.
cannam@147 89 KJ_FAIL_REQUIRE("Unknown expression type.");
cannam@147 90 }
cannam@147 91 }
cannam@147 92
cannam@147 93 class ValueImpl final: public Calculator::Value::Server {
cannam@147 94 // Simple implementation of the Calculator.Value Cap'n Proto interface.
cannam@147 95
cannam@147 96 public:
cannam@147 97 ValueImpl(double value): value(value) {}
cannam@147 98
cannam@147 99 kj::Promise<void> read(ReadContext context) {
cannam@147 100 context.getResults().setValue(value);
cannam@147 101 return kj::READY_NOW;
cannam@147 102 }
cannam@147 103
cannam@147 104 private:
cannam@147 105 double value;
cannam@147 106 };
cannam@147 107
cannam@147 108 class FunctionImpl final: public Calculator::Function::Server {
cannam@147 109 // Implementation of the Calculator.Function Cap'n Proto interface, where the
cannam@147 110 // function is defined by a Calculator.Expression.
cannam@147 111
cannam@147 112 public:
cannam@147 113 FunctionImpl(uint paramCount, Calculator::Expression::Reader body)
cannam@147 114 : paramCount(paramCount) {
cannam@147 115 this->body.setRoot(body);
cannam@147 116 }
cannam@147 117
cannam@147 118 kj::Promise<void> call(CallContext context) {
cannam@147 119 auto params = context.getParams().getParams();
cannam@147 120 KJ_REQUIRE(params.size() == paramCount, "Wrong number of parameters.");
cannam@147 121
cannam@147 122 return evaluateImpl(body.getRoot<Calculator::Expression>(), params)
cannam@147 123 .then([KJ_CPCAP(context)](double value) mutable {
cannam@147 124 context.getResults().setValue(value);
cannam@147 125 });
cannam@147 126 }
cannam@147 127
cannam@147 128 private:
cannam@147 129 uint paramCount;
cannam@147 130 // The function's arity.
cannam@147 131
cannam@147 132 capnp::MallocMessageBuilder body;
cannam@147 133 // Stores a permanent copy of the function body.
cannam@147 134 };
cannam@147 135
cannam@147 136 class OperatorImpl final: public Calculator::Function::Server {
cannam@147 137 // Implementation of the Calculator.Function Cap'n Proto interface, wrapping
cannam@147 138 // basic binary arithmetic operators.
cannam@147 139
cannam@147 140 public:
cannam@147 141 OperatorImpl(Calculator::Operator op): op(op) {}
cannam@147 142
cannam@147 143 kj::Promise<void> call(CallContext context) {
cannam@147 144 auto params = context.getParams().getParams();
cannam@147 145 KJ_REQUIRE(params.size() == 2, "Wrong number of parameters.");
cannam@147 146
cannam@147 147 double result;
cannam@147 148 switch (op) {
cannam@147 149 case Calculator::Operator::ADD: result = params[0] + params[1]; break;
cannam@147 150 case Calculator::Operator::SUBTRACT:result = params[0] - params[1]; break;
cannam@147 151 case Calculator::Operator::MULTIPLY:result = params[0] * params[1]; break;
cannam@147 152 case Calculator::Operator::DIVIDE: result = params[0] / params[1]; break;
cannam@147 153 default:
cannam@147 154 KJ_FAIL_REQUIRE("Unknown operator.");
cannam@147 155 }
cannam@147 156
cannam@147 157 context.getResults().setValue(result);
cannam@147 158 return kj::READY_NOW;
cannam@147 159 }
cannam@147 160
cannam@147 161 private:
cannam@147 162 Calculator::Operator op;
cannam@147 163 };
cannam@147 164
cannam@147 165 class CalculatorImpl final: public Calculator::Server {
cannam@147 166 // Implementation of the Calculator Cap'n Proto interface.
cannam@147 167
cannam@147 168 public:
cannam@147 169 kj::Promise<void> evaluate(EvaluateContext context) override {
cannam@147 170 return evaluateImpl(context.getParams().getExpression())
cannam@147 171 .then([KJ_CPCAP(context)](double value) mutable {
cannam@147 172 context.getResults().setValue(kj::heap<ValueImpl>(value));
cannam@147 173 });
cannam@147 174 }
cannam@147 175
cannam@147 176 kj::Promise<void> defFunction(DefFunctionContext context) override {
cannam@147 177 auto params = context.getParams();
cannam@147 178 context.getResults().setFunc(kj::heap<FunctionImpl>(
cannam@147 179 params.getParamCount(), params.getBody()));
cannam@147 180 return kj::READY_NOW;
cannam@147 181 }
cannam@147 182
cannam@147 183 kj::Promise<void> getOperator(GetOperatorContext context) override {
cannam@147 184 context.getResults().setFunc(kj::heap<OperatorImpl>(
cannam@147 185 context.getParams().getOp()));
cannam@147 186 return kj::READY_NOW;
cannam@147 187 }
cannam@147 188 };
cannam@147 189
cannam@147 190 int main(int argc, const char* argv[]) {
cannam@147 191 if (argc != 2) {
cannam@147 192 std::cerr << "usage: " << argv[0] << " ADDRESS[:PORT]\n"
cannam@147 193 "Runs the server bound to the given address/port.\n"
cannam@147 194 "ADDRESS may be '*' to bind to all local addresses.\n"
cannam@147 195 ":PORT may be omitted to choose a port automatically." << std::endl;
cannam@147 196 return 1;
cannam@147 197 }
cannam@147 198
cannam@147 199 // Set up a server.
cannam@147 200 capnp::EzRpcServer server(kj::heap<CalculatorImpl>(), argv[1]);
cannam@147 201
cannam@147 202 // Write the port number to stdout, in case it was chosen automatically.
cannam@147 203 auto& waitScope = server.getWaitScope();
cannam@147 204 uint port = server.getPort().wait(waitScope);
cannam@147 205 if (port == 0) {
cannam@147 206 // The address format "unix:/path/to/socket" opens a unix domain socket,
cannam@147 207 // in which case the port will be zero.
cannam@147 208 std::cout << "Listening on Unix socket..." << std::endl;
cannam@147 209 } else {
cannam@147 210 std::cout << "Listening on port " << port << "..." << std::endl;
cannam@147 211 }
cannam@147 212
cannam@147 213 // Run forever, accepting connections and handling requests.
cannam@147 214 kj::NEVER_DONE.wait(waitScope);
cannam@147 215 }